package com.huike.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.utils.CertificateBulider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.entity.Admin;
import com.huike.mapper.AdminMapper;
import com.huike.service.IAdminService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  鏈嶅姟瀹炵幇绫�
 * </p>
 *
 * @author Lwen
 * @since 2019-11-12
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

	@Override
	public IPage<Admin>  getMembersList(int page,String keyWord){
		QueryWrapper<Admin> wrapper = new QueryWrapper<>();
		if(keyWord==""){
			wrapper.orderByAsc("join_time");
		}else {
			wrapper.like("username", keyWord).or().like("uid", keyWord).orderByAsc("join_time");
		}
		Page<Admin> pages = new Page<>(page,10);
		IPage iPage = baseMapper.selectPage(pages,wrapper);
		return iPage;
	}

    @Override
    public Admin loginFun(Admin admin) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<Admin>();
        wrapper.lambda().eq(Admin::getUsername,admin.getUsername());
        List<Admin> list = list(wrapper);
        if (list.size()==0) {
            return null;
        }
        if (list.size()==1 && list.get(0).getPassword().equals(admin.getPassword())){
            return list.get(0);
        }
        return null;
    }

    @Override
    public IPage<Admin> listAdminByPage(int page, int limit) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        Page<Admin> pages = new Page<>(page,limit);
	    IPage iPage = baseMapper.selectPage(pages,wrapper);
        return iPage;
    }

    @Override
	public String getMemberCerticicate(String uid){
		Admin admin=getBaseMapper().selectOne(new QueryWrapper<Admin>().eq("uid",uid));
		String certificateUrl=null;
		if(admin.getCertificate()==null || admin.getCertificate()==""){
			certificateUrl=CertificateBulider.buildCertificate(admin);
			admin.setCertificate(certificateUrl);
			try{
				this.update(admin,new UpdateWrapper<Admin>().eq("uid",uid));
			}catch (Exception e){
				e.printStackTrace();
			}
		}else{
			certificateUrl=admin.getCertificate();
		}
		return certificateUrl;
	}

}
